package registration.webapi;

import registration.Address;
import registration.Customer;
import registration.CustomerRepository;
import registration.Name;
import registration.TelephoneNumber;
import registration.SalesManager;
import registration.SalesManagerRepository;

import java.time.LocalDate;

public class RegistrationServiceImpl implements RegistrationService {

    private final CustomerRepository customerRepo;

    private final SalesManagerRepository managerRepo;

    public RegistrationServiceImpl(CustomerRepository customerRepo, SalesManagerRepository managerRepo) {
        this.customerRepo = customerRepo;
        this.managerRepo = managerRepo;
    }

    @Override
    public CustomerDTO register(Name name, TelephoneNumber telephone, Address address) {
        // 取电话号里的长途区号，然后通过区号找到区域内的销售代表SalesManager
        String areaCode = telephone.getAreaCode();
        SalesManager areaSalesManager = managerRepo.findAreaSalesManager(areaCode);

        // 创建1条客户信息, 另外登记该客户所关联的销售经理，落盘，然后返回注册结果
        Customer c = new Customer();
        c.setName(name);
        c.setTelephone(telephone);
        c.setAddress(address);
        c.setMemberSince(LocalDate.now());
        c.setRelatedSalesManagerId(areaSalesManager.getId());
        Customer savedCustomer = customerRepo.save(c);
        return CustomerDTO.of(savedCustomer).with(areaSalesManager);
    }
}
